package com.infinit.easyreader.ui;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.infinit.easyreader.Biz.BookPageFactory;
import com.infinit.easyreader.R;
import com.infinit.easyreader.dao.BookDao;
import com.infinit.easyreader.dao.BookmarkDao;
import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.entity.Bookmark;
import com.infinit.easyreader.fragment.BookmarkFragment;
import com.infinit.easyreader.fragment.BooksFragment;
import com.infinit.easyreader.framework.PageWidget;
import com.infinit.easyreader.framework.SettingView;
import com.infinit.easyreader.framework.TabView;
import com.infinit.easyreader.utils.CommonUtils;
import com.infinit.easyreader.utils.Consts;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import app.minimize.com.seek_bar_compat.SeekBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReaderActivity extends AppCompatActivity implements Consts {
    public static final String SET_BG = "setBg";
    public static final String SET_BG_EXTRA = "bgExtra";
    public static final String SET_FONT_SIZE = "setFont";
    public static final String SET_FONT_EXTRA = "fontExtra";
    public static final String SET_BRIGHTNESS_FAIL = "setBrightnessFail";
    public static final String INTENT_BOOK = "intentBook";
    public static final int REQUEST_CODE_MARK = 99;
    @Bind(R.id.rbBookmark)
    RadioButton rbBookmark;
    @Bind(R.id.sbProgress)
    SeekBarCompat sbProgress;
    @Bind(R.id.rReader)
    RelativeLayout rReader;
    @Bind(R.id.ibBack)
    ImageButton ibBack;
    @Bind(R.id.rlTopBar)
    RelativeLayout rlTopBar;
    @Bind(R.id.rlBottomBar)
    RelativeLayout rlBottomBar;
    @Bind(R.id.rlProgress)
    RelativeLayout rlProgress;
    @Bind(R.id.settingView)
    SettingView settingView;
    @Bind(R.id.tabDic)
    TabView tabDic;
    @Bind(R.id.tabProgress)
    TabView tabProgress;
    @Bind(R.id.tabSettings)
    TabView tabSettings;
    Bitmap curBitmap;
    Bitmap nextBitmap;
    private int bgResId;
    private SharedPreferences preference;
    private boolean isAutoBrightness = false;
    private int lastBrightness;
    private String filePath;
    private Point screen;
    private PageWidget page;
    private BookPageFactory bookPage;
    private Canvas curCanvas;
    private Canvas nextCanvas;
    private int statusBarHeight;
    private BookDao bookDao;
    private int brightness;
    private String fontFamily;
    private int fontSize;
    private BroadcastReceiver receiver;
    private Book book;
    private List<Integer> markPositionList;
    private BookmarkDao bmDao;
    private long bookLength;
    private boolean isClickCenter;
    private boolean hasDragOver = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader);
        ButterKnife.bind(this);
        preference = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);
        //获取通知栏的高度
        statusBarHeight = CommonUtils.getStatusBarHeight(this);
        book = getIntent().getParcelableExtra(BooksFragment.FILE_PATH);
        filePath = book.getPath();
        //获取当前书籍的所有书签
        getAllBookmark();
        //获取当前设备的大小
        screen = new Point();
        getWindowManager().getDefaultDisplay().getSize(screen);
        //获取Page和BookPage
        page = new PageWidget(this);
        iniatateReader();
        //获取上次阅读的信息
        int lastReadPosition = getLastReadPosition();
        bookPage.setM_mbBufEnd(lastReadPosition);
        bookPage.setM_mbBufBegin(lastReadPosition);
        //获取TXT文件的大小
        File file = new File(book.getPath());
        bookLength = file.length();
        //打开书籍
        bookPage.setFontFamily(getTypeFace("方正兰亭"));
        try {
            bookPage.openbook(filePath);

        } catch (IOException e) {
            e.printStackTrace();
        }
        page.setScreen(screen.x, screen.y);
        rReader.addView(page, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        bookPage.onDraw(curCanvas);
        setListener();
        //设置BroadcastReceiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(SET_BG);
        filter.addAction(SET_FONT_SIZE);
        filter.addAction(SET_BRIGHTNESS_FAIL);
        receiver = new ReaderReceiver();
        registerReceiver(receiver, filter);
    }


    @OnClick({R.id.tabDic, R.id.tabProgress, R.id.tabSettings})
    public void showReaderSettings(View v) {
        int viewId = v.getId();
        rlTopBar.setVisibility(View.GONE);
        rlBottomBar.setVisibility(View.GONE);
        settingView.setVisibility(View.GONE);
        rlProgress.setVisibility(View.GONE);
        switch (viewId) {
            case R.id.tabSettings:
                settingView.setVisibility(View.VISIBLE);
                break;
            case R.id.tabProgress:
                rlProgress.setVisibility(View.VISIBLE);
                //设置当前的进度
                int percent = (int) (bookPage.getM_mbBufEnd() * 100 / bookLength);
                sbProgress.setProgress(percent);
                break;
        }

    }


    /**
     * 为返回按钮添加点击事件
     */


    @OnClick(R.id.ibBack)
    public void goBack() {
        this.finish();
    }


    /**
     * 作用：显示和隐藏操作栏
     */
    private void hideOrShowToolbar() {


        //当进度条或者阅读设置栏在显示时，将当前的所有View设置为gone
        if (settingView.getVisibility() == View.VISIBLE || rlProgress.getVisibility() == View.VISIBLE) {
            //显示工具栏
            rlTopBar.setVisibility(View.GONE);
            rlBottomBar.setVisibility(View.GONE);
            rlProgress.setVisibility(View.GONE);
            settingView.setVisibility(View.GONE);
        }
        //当上方的正在显示时，将当前的所有View设置为gone
        else if (rlTopBar.getVisibility() == View.VISIBLE) {
            rlTopBar.setVisibility(View.GONE);
            rlBottomBar.setVisibility(View.GONE);
            rlProgress.setVisibility(View.GONE);
            settingView.setVisibility(View.GONE);
        } else {
            rlTopBar.setVisibility(View.VISIBLE);
            //判断当前的页面是否为书签页面来显示书签按钮的状态
            rbBookmark.setChecked(false);
            if (isBookmarked(bookPage.getM_mbBufBegin())) {
                rbBookmark.setChecked(true);
            }
            rlBottomBar.setVisibility(View.VISIBLE);
        }

    }


    /**
     * 作用：判断当前设备的亮度调节模式
     */

    private boolean isAutoBrightness() throws Settings.SettingNotFoundException {

        return Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE)
                == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
    }


    /**
     * 作用：为部分控件设置监听器
     */
    private void setListener() {


        page.setOnTouchListener(new innerTouchListener());


        //为进度条设置监听器


        sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //根据进度来进行跳转
//                int progress = seekBar.getProgress();


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                int startPosition = (int) (bookLength * progress / 100);
                bookPage.setM_mbBufEnd(startPosition);
                bookPage.setM_mbBufBegin(startPosition);
                bookPage.clearM_lines();
                bookPage.onDraw(curCanvas);
                bookPage.onDraw(nextCanvas);
                //刷新页面
                page.refreshPages();
            }
        });

        //为书签按钮设置监听器

        tabDic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReaderActivity.this, BookmarkList.class);
                intent.putExtra(INTENT_BOOK, book);
                //requestCode在这里无用
                startActivityForResult(intent, REQUEST_CODE_MARK);
            }
        });


    }


    /**
     * 作用：调整屏幕亮度方法
     *
     * @param brightness 亮度值 取值范围 0-255
     */


    private void setBrightness(int brightness) {
        ContentResolver cr = getContentResolver();
        try {
            if (isAutoBrightness()) {
                //将亮度设置调整为手动设置
                Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
            //设置成为指定的亮度
            Settings.System.putFloat(cr, Settings.System.SCREEN_BRIGHTNESS, brightness);

        } catch (Settings.SettingNotFoundException e) {
            Toast.makeText(ReaderActivity.this, "调整亮度失败，请检查相关设置！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        //将亮度恢复到原有的亮度
        if (isAutoBrightness) {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
        } else {
            Settings.System.putFloat(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, lastBrightness);
        }
        super.onPause();
    }


    /**
     * 作用：取出数据库中的保存的上一次的阅读记录
     */
    private int getLastReadPosition() {
        bookDao = new BookDao(this);
        int nameIndex = filePath.lastIndexOf("/");
        String bookName = filePath.substring(nameIndex + 1);
        book = bookDao.findBook(bookName);
        return (int) book.getLastReadPosition();
    }


    /**
     * 生成翻页所需的两张bitmap
     *
     * @param bgPic bitmap的背景资源
     */
    private void setPageBg(int bgPic) {
        bookPage.setBgBitmap(genBitmapForReader(bgPic));
        //如果resId为黑色的话，将字体设置白色
        bookPage.setM_textColor(Color.parseColor(INIT_TEXT_COLOR));
        if (bgPic == R.drawable.reader_bg_black) {
            bookPage.setM_textColor(Color.WHITE);
        }
    }


    /**
     * 作用：生成PageWidget的两张bitmap
     */


    private void genCanvas() {

        curBitmap = Bitmap.createBitmap(screen.x, screen.y, Bitmap.Config.RGB_565);
        nextBitmap = Bitmap.createBitmap(screen.x, screen.y, Bitmap.Config.RGB_565);
        page.setBitmaps(curBitmap, nextBitmap);
        curCanvas = new Canvas(curBitmap);
        nextCanvas = new Canvas(nextBitmap);
    }


    /**
     * 重载方法，设置bookPage的一些属性
     */
    private void setBookPageSize() {
        bookPage = new BookPageFactory(screen.x, screen.y - statusBarHeight);
    }


    /**
     * 在退出阅读时，保存上一次的阅读信息
     */

    private void saveLastReadInfo() {
        int currentReadPosition = bookPage.getM_mbBufBegin();
        book.setLastReadPosition(currentReadPosition);
        book.setLastReadTime(CommonUtils.format2String(new Date()));
        bookDao.updateBooks(book);
        bookDao.close();
    }


    @Override
    protected void onDestroy() {
        saveLastReadInfo();
        unregisterReceiver(receiver);
        bmDao.close();
        bookDao.close();
        super.onDestroy();
    }


    /**
     * 方法，获取屏幕大小的bitmap作为阅读器的背景
     */

    private Bitmap genBitmapForReader(int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inMutable = true;
        options.inJustDecodeBounds = false;
        //获取资源图片的大小
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, options);
        bitmap = Bitmap.createScaledBitmap(bitmap, screen.x, screen.y - statusBarHeight, false);
        return bitmap;
    }


    /**
     * 作用：设置阅读器的字号
     */


    private void setFontSize(int fontSize) {
        bookPage.setM_fontSize(fontSize);
        bookPage.onDraw(curCanvas);
        bookPage.onDraw(nextCanvas);
    }


    /**
     * 方法，获取reader的初始信息
     */

    private void getIniatateInfo() {

        fontSize = preference.getInt(SETTING_FONTSIZE, 26);
        fontFamily = preference.getString(SETTING_FONTFAMINY, FontActivity.FONT_SYS);
        bgResId = preference.getInt(SETTING_BG, R.drawable.reader_bg_yellow);
        brightness = preference.getInt(SETTING_BRIGHTNESS, -1);

    }


    /**
     * 方法：初始化阅读器
     */

    private void iniatateReader() {
        getIniatateInfo();
        setBookPageSize();
        genCanvas();
        //设置书签页面的背景
        setPageBg(bgResId);
        //设置亮度
        //获取当前的亮度设置信息
        try {
            isAutoBrightness = isAutoBrightness();
            if (!isAutoBrightness) {
                lastBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            }
            //将进入阅读器之前的亮度信息保存到Preference中
            SharedPreferences.Editor editor = preference.edit();
            editor.putBoolean(SETTING_ISAUTOBRIGHTNESS, isAutoBrightness);
            editor.putInt(SETTING_LAST_BRIGHTNESS, lastBrightness);
            editor.apply();
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "获取亮度设置信息失败,请检查设置！", Toast.LENGTH_SHORT).show();
        }

        if (brightness != -1) {
            setBrightness(brightness);
        }
        //设置字体，待做
        bookPage.setFontFamily(getTypeFace(fontFamily));

        Log.d(TAG, "iniatateReader: " + bookPage.getM_fontSize());
        //设置字体大小
        bookPage.setM_fontSize(fontSize);
        Log.d(TAG, "iniatateReader: " + bookPage.getM_fontSize());

    }

    /**
     * 重写onActivityResult方法
     */


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case SettingView.FONT_REQUEST_CODE:
                    Button btFontFamily = (Button) settingView.findViewById(R.id.btFont);
                    String resultData = data.getStringExtra(FontActivity.FONT_RESULT);
                    if (FontActivity.FONT_SYS.equals(resultData)) {
                        //改变字体
                        bookPage.setFontFamily(null);
                    } else if (FontActivity.FONT_FZ.equals(resultData)) {
                        bookPage.setFontFamily(getTypeFace(resultData));
                    } else if (FontActivity.FONT_HY.equals(resultData)) {
                        bookPage.setFontFamily(getTypeFace(resultData));
                    }
                    //将SettingView中的字体设置成为指定文字
                    btFontFamily.setText(resultData);
                    //将字体信息保存在preference中
                    SharedPreferences.Editor editor = preference.edit();
                    editor.putString(SETTING_FONTFAMINY, resultData);
                    editor.apply();
                    //重新刷新View
                    if (!fontFamily.equals(resultData)) {
                        page.postInvalidate();
                    }
                    break;
                case REQUEST_CODE_MARK:
                    bookPage.clearM_lines();
                    bookPage.setM_mbBufEnd(data.getIntExtra(BookmarkFragment.MARKED_POSITION, 0));
                    bookPage.setM_mbBufBegin(data.getIntExtra(BookmarkFragment.MARKED_POSITION, 0));
                    bookPage.onDraw(curCanvas);
                    bookPage.onDraw(nextCanvas);
                    hideFunctionBar();
                    page.invalidate();
                    break;
            }
        }
    }

    /**
     * 作用：获取指定字体的TypeFace
     */


    private Typeface getTypeFace(String fontString) {
        Typeface typeface = Typeface.DEFAULT;
        if (FontActivity.FONT_FZ.equals(fontString)) {
            //加载方正兰亭
            typeface = Typeface.createFromAsset(getAssets(), "qckt.ttf");
        } else if (FontActivity.FONT_HY.equals(fontString)) {
            typeface = Typeface.createFromAsset(getAssets(), "jqfs.TTF");
        }
        return typeface;
    }

    /**
     * 作用：设置书签方法
     */

    @OnClick(R.id.rbBookmark)

    public void setBookmark() {
        //判断当前位置是否已经是书签页


        if (isBookmarked(bookPage.getM_mbBufBegin())) {
            //移除书签
            int startPosition = bookPage.getM_mbBufBegin();
            bmDao.deleteBookMarkAtPosition(startPosition);
            rbBookmark.setChecked(false);
            //从当前的书签列表中删除该书签
            markPositionList.remove(Integer.valueOf(startPosition));
            return;
        }
        //获取当前的开始位置
        int startPosition = bookPage.getM_mbBufBegin();
        String quote = bookPage.getQuote();
        Bookmark mark = new Bookmark();
        mark.setBook_id(book.getBookId());
        mark.setQuote(quote);
        mark.setPosition(startPosition);
        //插入到数据库
        bmDao.insertBookmark(mark);
        markPositionList.add(startPosition);
        //将书签按钮设置为已设置
        rbBookmark.setChecked(true);
    }

    /**
     * 作用：获取当前书籍的所有书签，并且取出所有进度保存到markPositionList中
     */

    private void getAllBookmark() {
        //获取当前书籍的所有书签
        bmDao = new BookmarkDao(this);
        markPositionList = new ArrayList<>();
        List<Bookmark> markList;
        markList = bmDao.findAllBookmark(book);
        for (Bookmark mark : markList) {
            markPositionList.add((int) mark.getPosition());
        }
        Collections.sort(markPositionList, new Comparator<Integer>() {
            @Override
            public int compare(Integer lhs, Integer rhs) {
                return lhs - rhs;
            }
        });
    }

    /**
     * 作用：判断当前的页面是否为书签页面
     * 逻辑：首先与最大值进行对比，如果大于最大，则判断为无
     * 然后与最小值进行比较，如果小于最小，则判断为无
     * 否则进行判断
     */

    private boolean isBookmarked(int startPosition) {
        return markPositionList.size() != 0 && startPosition <= markPositionList.get(markPositionList.size() - 1) && startPosition >= markPositionList.get(0) && markPositionList.contains(startPosition);
    }

    /**
     * 方法，隐藏界面上的功能界面
     */

    private void hideFunctionBar() {
        rlTopBar.setVisibility(View.GONE);
        rlBottomBar.setVisibility(View.GONE);
        rlProgress.setVisibility(View.GONE);
        settingView.setVisibility(View.GONE);


    }

    private class ReaderReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //处理背景方面的设置
            if (SET_BG.equals(action)) {
                int resId = intent.getIntExtra(SET_BG_EXTRA, -1);
                if (resId != -1) {
                    switch (resId) {
                        case R.drawable.reader_bg_black:
                            setPageBg(R.drawable.reader_bg_black);
                            break;
                        case R.drawable.reader_bg_lightblue:
                            setPageBg(R.drawable.reader_bg_lightblue);
                            break;
                        case R.drawable.reader_bg_white:
                            setPageBg(R.drawable.reader_bg_white);
                            break;
                        case R.drawable.reader_bg_lightgreen:
                            setPageBg(R.drawable.reader_bg_lightgreen);
                            break;
                        case R.drawable.reader_bg_yellow:
                            setPageBg(R.drawable.reader_bg_yellow);
                            break;
                    }
                    bookPage.onDraw(curCanvas);
                    page.invalidate();
                }
            }
            // 处理字体大小方面的设置
            if (SET_FONT_SIZE.equals(action)) {
                int fontSize = intent.getIntExtra(SET_FONT_EXTRA, -1);
                if (fontSize != -1) {
                    setFontSize(fontSize);
                    bookPage.getM_lines().clear();
                    bookPage.onDraw(curCanvas);
                    page.invalidate();
                }
            }

            //处理设置亮度失败的情况
            if (SET_BRIGHTNESS_FAIL.equals(action)) {
                Toast.makeText(ReaderActivity.this, "设置亮度失败,请检查设置！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 类，实现view.onTouchListener接口
     */

    private class innerTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v != page) {
                return true;
            }
            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    //当Down的时候，判断当前的点击位置是否为屏幕中间，如果是则消耗事件，然后将中间标识符置为true
                    if (Math.abs(event.getX() - screen.x / 2) < 30) {
                        hideOrShowToolbar();
                        isClickCenter = true;
                        return true;
                    }
                    hideFunctionBar();
                    isClickCenter = false;
                    //当不为中间时，记录lastClickX,并且清空动画，计算相应的坐标
                    page.calcCornerXY(event.getX(), event.getY());
                    page.abortAnimation();
                    if (hasDragOver) {
                        //bookPage.onDraw(curCanvas);
                        bookPage.onDraw(curCanvas);
                        //仍然进行点击翻页
                        if (event.getX() > screen.x / 2) {

                            //阅读下一页
                            try {
                                bookPage.nextPage();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (bookPage.islastPage()) {
                                return false;
                            }
                            bookPage.onDraw(nextCanvas);

                        } else {

                            //阅读上一页
                            try {
                                bookPage.prePage();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (bookPage.isfirstPage()) {
                                return false;
                            }
                            bookPage.onDraw(nextCanvas);
                        }
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    if (isClickCenter) {
                        return true;
                    }
                    //判断是否能翻过页
                    hasDragOver = page.canDragOver();
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (isClickCenter) {
                        return true;
                    }
                    break;
            }

            return page.doTouchEvent(event);
        }
    }


}
